package org.jim.server.demo.service.processor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.jim.core.ImChannelContext;
import org.jim.core.packets.ChatBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.demo.entity.ImMessage;
import org.jim.server.demo.service.impl.ImMessageServiceImpl;
import org.jim.server.processor.chat.BaseAsyncChatMessageProcessor;
import org.jim.server.processor.chat.DefaultAsyncChatMessageProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

/**
 * @Author lml
 *
 * 消息处理器
 */
public class ChatMessageServiceProcessor extends BaseAsyncChatMessageProcessor {

    private static Logger logger = LoggerFactory.getLogger(ChatMessageServiceProcessor.class);

    @Autowired
    private ImMessageServiceImpl imMessageService;

    @Override
    protected void doProcess(ChatBody chatBody, ImChannelContext imChannelContext) {

        logger.info("自定义处理器消息处理器！！！");

        if(ObjectUtil.isNull(chatBody)){
            logger.info("消息为空！");
            return ;
        }

        ImMessage imMessage = new ImMessage();

        String message =  JsonKit.toJSONString(chatBody);

        ChatBody company = JSONUtil.toBean(message, ChatBody.class);

        BeanUtil.copyProperties(company,imMessage,
                CopyOptions.create().setIgnoreError(true)
        );

        if(!ObjectUtil.isNull(company.getFrom())){
            imMessage.setFrom(company.getFrom());
        }

        logger.info("消息为：{}",imMessage);

        //落库
        try{
            imMessageService.save(imMessage);
        }catch (Exception e){
            logger.info("聊天记录落库失败！消息：{}",imMessage);
        }

    }
}
